const { chromium } = require('playwright');
const { axios } = require('axios');

// 封装获取表格数据的方法
async function getExtractedData(orderNumbers, extractionUsername, extractionPassword) {
    if (!orderNumbers || !Array.isArray(orderNumbers) || orderNumbers.length === 0) {
        throw new Error('orderNumbers参数必须是一个非空数组');
    }
    const browser = await chromium.launch({ 
        headless: false,
        timeout: 60000
    });
    const context = await browser.newContext();
    const page = await context.newPage();

    // 设置全局超时和重试策略
    page.setDefaultTimeout(30000);
    page.setDefaultNavigationTimeout(60000);

    // 登录部分增加重试
    await retryOperation(async () => {
        await page.goto('https://centric8.sncoia.com/WebAccess/login.html', { waitUntil: 'networkidle' });
        await page.waitForSelector('#LoginID', { state: 'attached' });
        await page.fill('#LoginID', extractionUsername);
        await page.fill('#Password', extractionPassword);
        await page.click('#loginButton_label');
        
        // 等待登录完成
        await page.waitForSelector('.csi-view-User-HeaderToolbar', { timeout: 45000 });
    }, 3);
    
    await page.getByRole('tab', { name: 'Product' }).click();
    await page.getByRole('tab', { name: 'Products' }).click();
        
    // const suspendButton = await page.waitForSelector('[title="Suspend all queries while configuring view"][aria-pressed="true"]', {
    //     timeout: 30000  // 最长等待30秒
    // });
        
    await page.getByRole('button', { name: 'Suspend', pressed: true }).click();
        
    const initialRowCount = await page.$$eval('.csi-view-table.tableView tbody tr', rows => rows.length);
    console.log(`初始行数: ${initialRowCount}`);
    // await suspendButton.click();

    // 轮询检查行数增加
    const maxWaitTime = 15000;
    const startTime = Date.now();
    let currentRowCount = initialRowCount;
    
    while (Date.now() - startTime < maxWaitTime) {
        currentRowCount = await page.$$eval('.csi-view-table.tableView tbody tr', rows => rows.length);
        if (currentRowCount > initialRowCount) {
            console.log(`当前行数: ${currentRowCount}`);
            break;
        }
        await page.waitForTimeout(500);
    }

    if (currentRowCount <= initialRowCount) {
        throw new Error('表格行数未增加，加载可能失败');
    }
    
    const LOADING_SELECTOR = '.csi-loading-circles';
    // const isLoadingPresent = await page.isVisible(LOADING_SELECTOR, { timeout: 5000 }).catch(() => false);
    const isLoadingPresent = await page.isHidden(LOADING_SELECTOR).catch(() => false);

    if (isLoadingPresent) {
        await page.waitForSelector(LOADING_SELECTOR, { state: 'hidden', timeout: 5000 });
        console.log('加载动画已消失，表格加载完成');
        await page.waitForTimeout(2000);        
    } else {
        console.log('未检测到加载动画，跳过等待');
    }
    // await page.waitForTimeout(5000);
    
    let allResults = [];

    for (const orderNumber of orderNumbers) {
        // 使用重试机制确保点击成功并显示下拉菜单
        await retryOperation(async () => {
            await page.locator('th[class="firstColumn csi-table-frozen-end"]').click();
            // 等待下拉菜单出现，如果没有出现则重试
            await page.waitForSelector('.dijitPopup .dijitInputInner', { state: 'visible', timeout: 5000 });
        }, 3, 1000);
        
        console.log('下拉菜单已成功显示');
        const inputElement = await page.$('.dijitPopup .dijitInputInner');
        if (inputElement) {
            console.log('元素存在');
            // 获取元素的属性以确认是否可编辑
            const tagName = await inputElement.getProperty('tagName');
            console.log(`元素标签名: ${await tagName.jsonValue()}`);
        } else {
            console.log('元素不存在');
        }    
        await page.focus('.dijitPopup .dijitInputInner');
        await page.type('.dijitPopup .dijitInputInner', orderNumber, { delay: 100 });
        
        const isChecked = await page.evaluate((orderNumber) => {
            const items = Array.from(document.querySelectorAll('.dijitMenuItem'));
            const targetItem = items.find(item => {
                const label = item.querySelector('label.dijitMenuItemLabel');
                return label && label.textContent.trim() === `${orderNumber} (1)`;
            });
        
            if (!targetItem) {
                console.log('未找到对应选项');
                return false;
            }
    
            const checkbox = targetItem.querySelector('input[type="checkbox"]');
            if (!checkbox) {
                console.log('该选项没有 checkbox');
                return false;
            }
    
            return checkbox.checked;
        }, orderNumber);
    
        if (!isChecked) {
            // 如果未选中，则点击勾选
            await page.click(`label.dijitMenuItemLabel:has-text("${orderNumber} (1)")`);
            console.log('已选中该选项');
        } else {
            console.log('该选项已经选中');
        }
    
        await page.click('span.csi-table-header-content:has-text("Image")');
        
        if (isLoadingPresent) {
            await page.waitForSelector(LOADING_SELECTOR, { state: 'hidden', timeout: 5000 });
            console.log('加载动画已消失，表格加载完成');
            await page.waitForTimeout(2000);
        } else {
            console.log('未检测到加载动画，跳过等待');
        }
        await page.waitForTimeout(3000);
    }
    await page.waitForTimeout(10000);
    // 4. 获取表格数据
    const tableContainer = await page.$('.csi-table-container-inner.csi-table-hide-extra-column.csi-table-frozen.csi-table-frozen-scroll-min');
    const targetTable = await tableContainer.$('.csi-view-table.tableView.csi-view-table-fixed-body');
    // const rows = await targetTable.$$('tbody tr');

    const tbody = page.locator('//tbody[@data-dojo-attach-point="bodyNode"]').last();
    const rows = tbody.locator('tr');
    const rowCount = await tbody.evaluate(element => {
        return element.querySelectorAll('tr').length;
    });

    // 检查表格行数是否等于单号数量
    // const totalRows = rows.length;
    const orderCount = orderNumbers.length;
    console.log(`表格总行数: ${rowCount}, 单号数量: ${orderCount}`);
    
    if (rowCount !== orderCount) {
        console.log(`警告: 表格行数(${rowCount})与单号数量(${orderCount})不匹配`);
    }
    
    const results = [];
    
    // 遍历每一行，验证product值是否与单号匹配
    for (let i = 0; i < rowCount; i++) {
        const row = rows.nth(i);
        
        // 获取第一列（Node Name）
        const productNode = row.locator('td[data-csi-heading="Node Name::0"] a');
        let product = '';
        try {
            product = await productNode.textContent();
            product = product ? product.trim() : '';
        } catch (error) {
            console.log(`第${i + 1}行获取product失败:`, error.message);
        }
        
        console.log('product: ', product)
        // 如果 product 为空字符串，则跳过该行
        if (!product) {
            console.log(`第${i + 1}行的product为空，跳过该行`);
            continue;
        }
        
        console.log('product: ', product)

        // 检查当前行的product是否在orderNumbers中
        const isProductInOrderNumbers = orderNumbers.includes(product);
        
        if (!isProductInOrderNumbers) {
            console.log(`第${i + 1}行的product (${product}) 不在单号列表中，等待5秒后重新检查...`);
            await page.waitForTimeout(5000);
            
            // 重新获取product值
            const updatedProductNode = row.locator('td[data-csi-heading="Node Name::0"] a');
            try {
                product = await updatedProductNode.textContent();
                product = product ? product.trim() : '';
            } catch (error) {
                console.log(`重新获取product失败:`, error.message);
            }
            
            if (orderNumbers.includes(product)) {
                console.log(`重新检查后，第${i + 1}行的product (${product}) 在单号列表中`);
            } else {
                console.log(`重新检查后，第${i + 1}行的product (${product}) 仍不在单号列表中`);
            }
        }
        
        // 获取第三列（Short Designation）
        const shortDescNode = row.locator('td[data-csi-heading*="ShortDesignation2_String"]');
        let shortDesc = '';
        try {
            shortDesc = await shortDescNode.textContent();
            shortDesc = shortDesc ? shortDesc.trim() : '';
        } catch (error) {
            console.log(`第${i + 1}行获取shortDesc失败:`, error.message);
        }
        
        // 获取第六列（Supplier Name）
        const supplierNode = row.locator('td[data-csi-heading="AUC_Style_DefSuplierName_String::0"]');
        let supplier = '';
        try {
            supplier = await supplierNode.textContent();
            supplier = supplier ? supplier.trim() : '';
        } catch (error) {
            console.log(`第${i + 1}行获取supplier失败:`, error.message);
        }
        
        // 获取product SKU
        const productSKUNode = row.locator('td[data-csi-heading="Node Name:Child:RealizedProducts:0{RealizedProducts}"]');
        let productSKU = '';
        try {
            productSKU = await productSKUNode.textContent();
            productSKU = productSKU ? productSKU.trim() : '';
        } catch (error) {
            console.log(`第${i + 1}行获取productSKU失败:`, error.message);
        }

        // 解析product字段
        let campaign = '';
        let department = '';
        if (product) {
            console.log('有product')
            const parts = product.split('-');
            if (parts.length >= 4) {
                campaign = parts[0]; // 去掉开头的P
                department = parts[1];
            }
        }
        
        // 添加到结果数组
        results.push({
            product,
            'Product Short Description': shortDesc,
            'Main Supplier': supplier,
            campaign,
            department,
            location: 'SH',
            productSKU,
        });
    }
    
    // 验证是否所有单号都有对应的数据行
    const extractedProducts = results.map(r => r.product);
    const missingOrderNumbers = orderNumbers.filter(orderNum => !extractedProducts.includes(orderNum));
    
    if (missingOrderNumbers.length > 0) {
        console.log(`警告: 以下单号未找到对应的数据行: ${missingOrderNumbers.join(', ')}`);
    }
    
    console.log(`成功提取 ${results.length} 行数据`);
    allResults = allResults.concat(results);

    console.log('Extracted data:', allResults);  
    await browser.close();
    return allResults;
}

// 添加重试函数
async function retryOperation(operation, maxRetries = 3, delay = 1000) {
    let lastError;
    
    for (let i = 0; i < maxRetries; i++) {
        try {
            await operation();
            return;
        } catch (error) {
            lastError = error;
            console.log(`操作失败，重试 ${i + 1}/${maxRetries}:`, error.message);
            await new Promise(resolve => setTimeout(resolve, delay * (i + 1)));
        }
    }
    
    throw lastError;
}

module.exports = { 
    getExtractedData
};